<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\technician\controller;

/** 控制器类引入区 **/

/** 模型类引入区 **/


use app\common\model\Banner;
use app\common\model\Goods;
use app\common\model\Goodscat;
use app\common\model\HandCard;
use app\common\model\Ivtlog;
use app\common\model\News;
use app\common\model\Newscat;
use app\common\model\Notic as NoticModel;
use app\common\model\Order as OrdersM;
use app\common\model\Orderproject;
use app\common\model\Position;
use app\common\model\Project;
use app\common\model\Room;
use app\common\model\Store;
use app\common\model\Users as UsersM;

/** 核心或第三方类引入区 **/

use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use app\common\service\VoiceService;
use think\Db;
use my\Wx;
use think\facade\Cache;
use think\helper\Hash;
use think\Model;
use app\common\model\Order;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Home
{
    public $noNeedLogin = [''];

    /**
     *  首页接口
     *
     **/
    public function index()
    {
        if ($this->request->isPost()) {
            $room = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $roomRes = Db::name('qt_room')->where('id', $room)->find();
            $orderprojectModel = new Orderproject();
            $nowproject = $orderprojectModel->getRoomProject($this->store_id, $room, $this->userInfo['id']);
            $data = array(
                'nowproject' => $nowproject,
                'store_name' => Store::where('id', $this->store_id)->value('name'),
                'room_name' => $roomRes['name'],
                'store_id' => $this->store_id,
            );
            $this->result('获取成功', $data, 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 房间状态
     */
    public function room_status()
    {

        if ($this->request->isPost()) {
            $page = $this->request->post('page', '1');
            $limit = $this->request->post('limit', '10');
            $type = $this->request->post('type', '0');
            $keyword = $this->request->post('keyword', '0');
            $RoomModel = new Room();
            $list = $RoomModel->roomlist($type, $page, $limit, $keyword, $this->store_id);
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     *
     * 房间详情
     */
    public function room_info()
    {

        if ($this->request->isPost()) {
            $roomId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $orderId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('order_project_id');
            $RoomModel = new Room();
            $list = $RoomModel->roominfo($roomId, $this->store_id, $orderId);
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 上钟
     */
    public function start_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $id = $this->request->post('id');//订单ID
            $user_id = $this->userInfo['id'];
            if($this->storeInfo['type'] != '1'){
                if(!isset($getData['hand_card_name']) || empty($getData['hand_card_name'])){
                    $this->result('请填写手牌号', '', 204);
                }
            }
            //更新手牌号
            if (isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])) {
                $handCardData = Db::name('qt_hand_card')
                    ->where(['store_id' => $this->userInfo['store_id'], 'name' => $getData['hand_card_name']])
                    ->find();
                if (empty($handCardData)) {
                    $this->result('无效的手牌', '', 204);
                }

                if ($handCardData['status'] != '2') {
                    $this->result('手牌未发放', '', 204);
                }
                //检测停牌
                $checkStatus = HandCard::checkStatus($handCardData['id']);
                if ($checkStatus == false) {
                    $this->result('手牌状态有问题', '', 204);
                }
                //检测最大消费金额
                $money = Db::name('qt_order_project')->where('is_delete',2)->where(['id' => $getData['order_id']])->value('price');
                $checkMoney = HandCard::checkMaxMoney($handCardData['id'], $money);
                if ($checkMoney == false) {
                    $this->result('超出手牌最大消费金额', '', 204);
                }
                Db::name('qt_order_project')->where(['id' => $getData['order_id']])->update(['hand_card_id' => $handCardData['id']]);
                //查询总金额
                $money = Db::name('qt_order_project')->where('is_delete',2)->where(['id' => $getData['order_id']])->value('price');
                //给手牌加金额
                Db::name('qt_hand_grant')
                    ->where(['hand_card_id' => $handCardData['id']])
                    ->where(['status' => '2'])
                    ->setInc('money', $money);
            }
            //判断提成模式
            $orderProjectData = Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->find();
            if($this->storeInfo['receiver_order_commission_type'] == '3'){
                if($orderProjectData['old_name'] != null || $orderProjectData['old_name'] != ''){
                    //更新提成记录
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$getData['order_id']])->update(['receiver'=>0]);
                    //更新订单提成
                    Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->update(['receiver'=>0]);
                }
            }
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($id, $user_id, '1',$this->userInfo);
            if ($res['status']) {
                //上钟成功播报
                $voiceResult = VoiceService::createVoice('上钟成功');
                if ($voiceResult['code'] == 0) {
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'], '上钟成功', $voiceResult['data'], '5', '3', $user_id);
                }
                $this->result('上钟成功', '', '200');
            } else {
                $this->result('上钟失败', $res['msg'], '204');
            }
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     *下钟操作
     */
    public function end_project()
    {
        if ($this->request->isPost()) {
            $user_id = $this->userInfo['id'];
            $orderQueue = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id'], 'store_id' => $this->userInfo['store_id']])->find();
            $orderData = Db::name('qt_order_project')->where('is_delete',2)->where(['id' => $orderQueue['order_project_id']])->find();
            $time = ($orderData['end_time'] - time()) / 60;
            $time = ceil($time);
            if ($this->storeInfo['advance_down_block'] != '0') {
                if ($time > $this->storeInfo['advance_down_block']) {
                    $this->result('未到下钟时间，暂时不能下钟', '', 204);
                }
            }
            //查询当前技师的其他的项目
            $orderProjectData = Db::name('qt_order_project')->where('is_delete',2)->where(['engineer_id' => $this->userInfo['id']])->select();
            foreach ($orderProjectData as $key => $value) {
                $OrderprojectModel = new Orderproject();
                $res = $OrderprojectModel->start_project($value['id'], $value['engineer_id'], '2', $this->userInfo);
            }
            //判断房间是否还有未支付的项目订单
            $noPayOrderProject = Db::name('qt_order_project')
                ->where(['room_id' => $orderData['room_id'], 'pay_status' => '0','is_delete'=>'2','is_change'=>'1'])
                ->find();
            if ($noPayOrderProject == null) {
                Db::name('qt_order')->where(['id' => $orderData['order_id']])->update(['pay_status' => '2']);
            }
            if ($res['status']) {
                //下钟成功播报
                $voiceResult = VoiceService::createVoice('下钟成功');
                if ($voiceResult['code'] == 0) {
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'], '下钟成功', $voiceResult['data'], '6', '3', $user_id);
                }
                //下钟动排
                $storeRule = Db::name('qt_queue_rule')->where(['type' => '1', 'store_id' => $this->userInfo['store_id']])->find();
                if($storeRule['is_down_act'] == '1'){
                    $endSort = Db::name('qt_order_queue')
                        ->where(['store_id' => $this->userInfo['store_id']])
                        ->order('sort desc')
                        ->find();
                    Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id'],'user_id'=> $this->userInfo['id']])->update(['sort'=>$endSort['sort'] + 1]);
                }
                //判断是否有多钟排位
                $manyQueueData = Db::name('qt_order_many_queue')
                    ->field('queue.*,rule.is_down_act')
                    ->alias('queue')
                    ->leftJoin('qt_many_queue_rule rule','rule.id = queue.many_queue_id')
                    ->where([
                        'queue.store_id'=>$this->userInfo['store_id'],
                        'queue.user_id'=>$this->userInfo['id'],
                        'queue.project_id'=>$orderProjectData[0]['project_id']
                    ])->find();
                if($manyQueueData['is_down_act'] == '1'){
                    $endSort = Db::name('qt_order_many_queue')
                        ->where(['many_queue_id' => $manyQueueData['many_queue_id']])
                        ->max('sort');
                    Db::name('qt_order_many_queue')->where(['id'=>$manyQueueData['id'],])->update(['sort'=>$endSort + 1]);
                }
                $this->result('下钟成功', '', '200');
            } else {
                $this->result('下钟失败', $res['msg'], '204');
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 加钟
     */
    public function add_engineer()
    {
        if ($this->request->isPost()) {
            $project_id = $this->request->post('project_id');//性别 1男2 女
            $roomId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->add_project($this->store_id, $project_id, $roomId);
            if ($res['status']) {
                $this->result('加钟成功', '', '200');
            } else {
                $this->result('更换失败', $res['msg'], '204');
            }

        } else {
            $this->result('非法请求', '', 204);
        }

    }

    /**
     * 更新技师
     */
    public function change_engineer()
    {
        if ($this->request->isPost()) {
            $sex = $this->request->post('sex', '1');//性别 1男2 女
            $project_id = $this->request->post('project_id');//性别 1男2 女
            $roomId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->change_engineer($this->store_id, $project_id, $roomId, $sex, $this->userInfo['id']);

            if ($res['status']) {
                $this->result('更换成功', '', '200');
            } else {
                $this->result('更换失败', $res['msg'], '204');
            }

        } else {
            $this->result('非法请求', '', 204);
        }

    }

    //获取当前房间所有的项目
    public function get_all_project()
    {
        if ($this->request->isPost()) {
            $roomId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $orderprojectModel = new Orderproject();
            $nowproject = $orderprojectModel->getRoomProject($this->store_id, $roomId, $this->userInfo['id']);
            $info = array(
                'list' => $nowproject
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    //换项目获取项目列表
    public function get_change_project()
    {
        if ($this->request->isPost()) {
            $roomId = Db::name('qt_order_queue')->where(['user_id' => $this->userInfo['id']])->value('room_id');
            $orderprojectModel = new Orderproject();
            $nowproject = $orderprojectModel->getChangeProject($this->store_id, $roomId, $this->userInfo['id']);
            $info = array(
                'list' => $nowproject
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 更换项目
     */
    public function change_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //老项目订单
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id', $getData['order_project_id'])->find();
            if ($orderProject['project_id'] == $getData['project_id']) {
                $this->result('所换项目与原来一致，请重新选择', '', 204);
            }
            //新项目
            $newProject = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            $oldProject = Db::name('qt_project')->where('id', $orderProject['project_id'])->find();
            if (!empty($orderProject['start_time'])) {
                $startTime = $orderProject['start_time'];
                if ($newProject['time'] > $oldProject['time']) {
                    $ceil = $newProject['time'] - $oldProject['time'];
                    $endTime = $orderProject['end_time'] + ($ceil * 60);
                } else {
                    $ceil = $oldProject['time'] - $newProject['time'];
                    $endTime = $orderProject['end_time'] - ($ceil * 60);
                }
            } else {
                $startTime = null;
                $endTime = null;
            }
            //新订单信息
            $newOrderProjectInsert = [
                'store_id' => $orderProject['store_id'],
                'name' => $newProject['name'],
                'old_name' => $oldProject['name'],
                'created_order_id' => $orderProject['created_order_id'],
                'order_id' => $orderProject['order_id'],
                'engineer_id' => $getData['engineer_id'],
                'project_id' => $getData['project_id'],
                'room_id' => $orderProject['room_id'],
                'hand_card_id' => $orderProject['hand_card_id'],
                'order_type' => '1',
                'num' => $orderProject['num'],
                'price' => $newProject['price'],
                'status' => $orderProject['status'],
                'is_add' => '1',
                'is_change' => '1',
                'created_time' => time(),
                'sale_id' => $this->userInfo['id'],
                'start_time' => $startTime,
                'end_time' => $endTime,
            ];
            //插入新项目
            $newProjectId = Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
            //更新老项目数据
            Db::name('qt_order_project')->where(['id' => $getData['order_project_id']])->update(['status' => '5', 'is_change' => '3']);
            if ($startTime == null) {
                $workStatus = '5';
                $queueStatus = '2';
            } else {
                $workStatus = '4';
                $queueStatus = '3';
            }
            Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->update([
                    'old_name' => $orderProject['name'],
                    'start_time' => $startTime,
                    'status' => $queueStatus,
                    'end_time' => $endTime,
                    'room_id' => $orderProject['room_id'],
                    'order_project_id' => $newProjectId
                ]);
            Db::name('qt_users')->where(['id' => $orderProject['engineer_id']])->update(['work_status' => $workStatus]);
            //判断接待提成规则
            //1=按下单人项目不管技师做什么项目，2=按技师上钟项目不管下单人下什么项目，3=下单人下单项目和技师上钟项目必须相同才有提成
            if ($this->storeInfo['receiver_order_commission_type'] == '2') {
                //删除之前的提成并插入新的接待提成和技师提成
                Db::startTrans();

                try {
                    //删除订单提成
                    Db::name('qt_commission_log')->where(['type' => '1', 'order_project_id' => $orderProject['id']])->delete();
                    //插入新的提成
                    $project = Db::name('qt_project')->where('id', $getData['project_id'])->find();
                    //普通提成
                    $commission = new OrdinaryService();
                    $commission = $commission->showCommission('1', '1', $project);
                    //计算接待提成
                    $receiver = new ReceiverService();
                    $receiver = $receiver->showCommission('1', '1', $project);
                    if ($this->storeInfo['floor_commission_type'] == '1') {
                        $cashierId = $orderProject['created_order_id'];
                    } else {
                        $cashierId = $orderProject['created_order_id'];
                    }
                    $insert = [
                        'store_id' => $this->storeInfo['id'],
                        'cashier_id' => $cashierId,//接待人
                        'user_id' => $getData['engineer_id'],//技师
                        'room_id' => $orderProject['room_id'],
                        'money' => $newProject['price'],
                        'commission' => $commission,//技师提成
                        'receiver' => $receiver,//接待提成
                        'product_id' => $orderProject['project_id'],
                        'type' => '1',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $newProjectId,
                        'status' => $orderProject['order_type'],
                        'is_add' => $orderProject['order_type'],
                    ];
                    Db::name('qt_commission_log')->insert($insert);
                    //安排等位
                    $waitRes = Db::name('qt_wait')
                        ->where(['store_id' => $orderProject['store_id'], 'status' => '1','delay_time'=>'0'])
                        ->where('room_id', 'neq', $orderProject['room_id'])
                        ->order('is_first desc id desc')
                        ->select();
                    if (!empty($waitRes)) {
                        $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id', $waitRes[0]['order_id'])->select();
                        $model = new Order();
                        $model->calculation($waitRes[0]['room_id'], $waitRes[0]['project_id'], $waitRes[0]['sex'], '1', $orderProject);
                        Db::name('qt_wait')->where(['id' => $waitRes[0]['id']])->update(['status' => '2']);
                    }
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('操作失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
                }
            }
            //如果有手牌先减去老项目金额，再加新的金额
            if ($orderProject['hand_card_id'] != '') {
                $handGrant = Db::name('qt_hand_grant')
                    ->where(['hand_card_id' => $orderProject['hand_card_id'], 'status' => '2'])
                    ->order('id desc')
                    ->find();
                if (!empty($handGrant)) {
                    Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setDec('money', $orderProject['price']);
                    Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setInc('money', $newProject['price']);
                } else {
                    $this->result('手牌状态不正确，无法换项', '', 204);
                }
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    //获取自由开单的项目列表
    public function get_free_project()
    {
        if ($this->request->isPost()) {
            $ProjectModel = new Project();
            $list = $ProjectModel->getProjectList($this->userInfo['store_id'], '0', '0', '0', '1', '', '100');
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    //获取房间列表
    public function get_roomlist()
    {
        if ($this->request->isPost()) {
            $RoomModel = new Room();
            $list = $RoomModel->roomlist(0, 1, '100', '', $this->userInfo['store_id']);
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 自由开单
     */
    public function add_free_project()
    {
        if ($this->request->isPost()) {
            $room_id = $this->request->post('room_id');
            $project_id = $this->request->post('project_id');
            $ProjectModel = new Project();
            $list = $ProjectModel->getProjectList($this->userInfo['store_id'], '0', '0', '0', '1', '', '100');
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }

    }


    /**
     * 技师加钟
     */
    public function addClock()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id']) || empty($getData['num'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id', $find['order_project_id'])->find();
            $project = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            $add = Db::name('qt_users')->where('id', $getData['engineer_id'])->value('is_add');
            //下新项目
            $insertOrderProject = [
                'store_id' => $orderProject['store_id'],
                'name' => $project['name'],
                'created_order_id' => $this->userInfo['id'],
                'order_id' => $orderProject['order_id'],
                'engineer_id' => $orderProject['engineer_id'],
                'project_id' => $getData['project_id'],
                'room_id' => $orderProject['room_id'],
                'hand_card_id' => $orderProject['hand_card_id'],
                'old_card_id' => $orderProject['old_card_id'],
                'order_type' => '5',
                'num' => '1',
                'price' => $project['add_block_price'],
                'status' => 2,
                'is_add' => $add,
                'start_time' => time(),
                'end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60),
                'is_change' => '1',
                'created_time' => time(),
            ];
            try {
                //更新项目订单状态
                Db::name('qt_order_project')->where('id', $orderProject['id'])->update(['end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60), 'status' => '2']);
                Db::name('qt_order_project')->insert($insertOrderProject);
                Db::name('qt_order_queue')->where('user_id', $orderProject['engineer_id'])->update(['end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60)]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('加钟失败', '', 204);
            }
            $this->result('加钟成功', '', 200);


        }
    }


    /**
     * 退技师
     */
    public function retreatEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            //退技师时间限制
            if ($find['start_time'] != null) {
                $time = (time() - $find['start_time']) / 60;
                $time = ceil($time);
                if ($this->storeInfo['back_engineer_block'] != '0') {
                    if ($time > $this->storeInfo['back_engineer_block']) {
                        $this->result('上钟超过设置时间，无法退技师', '', 204);
                    }
                }
            }
            //退技师支付状态限制
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where(['id' => $find['order_project_id']])->find();
            if ($orderProject['pay_status'] == '1') {
                $this->result('该项目已经支付，无法退技师', '', 204);
            }
            try {
                Db::startTrans();
                //恢复技师原来位置
                if (empty($find['old_sort'])) {
                    $update['sort'] = $find['sort'];
                } else {
                    $update['sort'] = $find['old_sort'];
                }
                $update['room_id'] = null;
                $update['project_id'] = null;
                $update['order_project_id'] = null;
                $update['start_time'] = null;
                $update['end_time'] = null;
                $update['real_time'] = null;
                $update['order_user_id'] = null;
                Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])->update($update);
                //更新订单状态
                Db::name('qt_order_project')->where('id', $find['order_project_id'])->update(['is_change' => '2', 'status' => '4', 'return_time' => time()]);
                //更新房间状态
                Db::name('qt_room')->where('id', $find['room_id'])->update(['status_id' => '10']);
                //更新技师状态
                Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '1']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('操作失败', '', 204);
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 技师自由开单
     */
    public function freeBilling()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id']) || empty($getData['num']) || empty($getData['engineer_id']) || empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //判断房间是否开房
            $room = Db::name('qt_room')->where(['id' => $getData['room_id']])->find();
            $statusArray = ['2', '3', '10'];
            if (!in_array($room['status_id'], $statusArray)) {
                $this->result('房间状态有问题，暂不支持下单', '', 204);
            }
            $userInfo = Db::name('qt_users')->where(['id' => $getData['engineer_id']])->find();
            if ($userInfo['work_status'] != '1') {
                $this->result('当前技师状态有问题，暂不支持下单', '', 204);
            }

            //判断技师是否可以自由开单
            $res = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_project p', 'p.id = up.project_id')
                ->leftJoin('qt_users_auth au', 'au.engineer_id = up.engineer_id')
                ->where(['up.engineer_id' => $getData['engineer_id'], 'p.is_free_order' => '1', 'au.is_open' => '1'])
                ->find();
            if (empty($res)) {
                $this->result('当前技术没有自由开单权限，或技师不会做此项目', '', 204);
            }
            //项目信息
            $projectRes = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            //判断总订单是否存在
            $orderCheck = Db::name('qt_order')->where(['room_id' => $getData['room_id'], 'pay_status' => '1'])->find();
            try {
                if (empty($orderCheck)) {
                    $orderInsert['order_no'] = ordersn();
                    $orderInsert['store_id'] = $projectRes['store_id'];
                    $orderInsert['room_id'] = $getData['room_id'];
                    $orderInsert['total_num'] = '1';
                    $orderInsert['total_price'] = $projectRes['price'];
                    $orderInsert['status'] = '1';
                    $orderInsert['order_type'] = '1';
                    $orderInsert['delay'] = 0;
                    $orderInsert['time_type'] = 1;
                    $orderInsert['created_time'] = time();
                    $orderModel = new Order();
                    $orderRes = $orderModel::create($orderInsert);
                    $orderId = $orderRes->id;
                } else {
                    $orderId = $orderCheck['id'];
                }
                //生成订单附表
                $orderProjectInsert = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $this->userInfo['id'],
                    'order_id' => $orderId,
                    'engineer_id' => $this->userInfo['id'],
                    'project_id' => $getData['project_id'],
                    'room_id' => $getData['room_id'],
                    'order_type' => '1',
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'creater_room' => '',
                    'created_time' => time(),
                    'sale_id' => $this->userInfo['id'],
                ];
                $orderProjectId = Db::name('qt_order_project')->insertGetId($orderProjectInsert);
                //子订单信息
                $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id', $orderProjectId)->find();
                //用户信息
                $userInfo = Db::name('qt_users')->where(['id' => $getData['engineer_id']])->find();
                //最大的sort
                $endSort = Db::name('qt_order_queue')->where(['store_id' => $orderProject['store_id']])->max('sort');
                try {
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_order_project')->where(['id' => $orderProject['id']])->update(['engineer_id' => $getData['engineer_id']]);
                    //更新技师状态
                    Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '5', 'room_id' => $getData['room_id']]);
                    //更新房间订单号
                    Db::name('qt_room')->where(['id' => $getData['room_id']])->update(['order_id' => $orderProject['order_id']]);
                    //更新技师排班数据
                    $updateQueue['room_id'] = $getData['room_id'];
                    $updateQueue['project_id'] = $getData['project_id'];
                    $updateQueue['order_project_id'] = $orderProject['id'];
                    $updateQueue['order_user_id'] = $orderProject['created_order_id'];
                    $updateQueue['day'] = date("Y-m-d");
                    $updateQueue['type_id'] = $userInfo['type_id'];
                    $updateQueue['status'] = '2';
                    $updateQueue['sort'] = $endSort + 1;
                    Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])->update($updateQueue);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('下单失败', '', 204);
                }
            } catch (Exception $e) {
                print $e->getMessage();
                exit();
            }
            $this->result('下单成功', '', 200);
        }
    }


}
